var pays={};
var ptype = 'wxpay'; 
var w=null;
var url = '';
var uid, ws, doctorid, doctorname, doctoravatar, videoprice, overPay = '0', money, wenzhen;
var balance;	//余额支付
document.addEventListener('plusready', function(){
	uid = plus.storage.getItem('uid');
	balance = plus.storage.getItem('money');
	ws = plus.webview.currentWebview();
	doctorid = ws.doctorid;//医生id
	doctorname = ws.doctorname;//医生名
	doctoravatar = ws.doctoravatar;//医生头像
	money = ws.videoprice;//视频价格
	console.log(doctorid+" "+doctorname+" "+doctoravatar+" "+money+" "+balance);
	$('.name').text(doctorname);
	$('.userPic').attr('src', getAvatar(doctoravatar));
	plus.nativeUI.closeWaiting();
	var date = new Date();
	var dat = parseInt(date.getTime()) + (1000 * 60 * 30);//距当前时间往后推半个小时
    $('#result').text(cdate(dat));
	// 获取支付通道
	plus.payment.getChannels(function(channels){
		for(var i in channels){
			var channel=channels[i];
			pays[channel.id]=channel;
			checkServices(channel);
		}
	},function(e){
		outLine("获取支付通道失败："+e.message);
	});
	//点击确认
	$('.rz-btn').on('tap', function(){
		var xuan = get_unix_time($('#result').text());		//选择的时间戳
		var dang = Date.parse(new Date());
		dang = dang.toString().substring(0, dang.toString().length - 3);	//当前时间
		console.log((xuan-dang)/60/30);
		//判断预约事件是否选在半小时后
		if((xuan-dang)/60/30 < 0.9){
			toast('预约时间须选择半个小时后');return;
		}
//		payOrder();//测试
		if(overPay == '1'){		//判断是否支付
//			toast('预约成功,问诊号：'+wenzhen);
			toast('预约成功');
			ws.close();
		}else{
			toast('您还未支付，请先支付');
		}
	})
	//选择支付方式
	$('#picture-btn').on('tap', function(){
		$('.zhifzzao').show();
    	$('.zhiftc').slideDown();
	})
	//支付方式
	$('.zhiftc div').on('tap', function(){
		switch($(this).index()){
			case 1://点击微信支付
			toast('待接口提供');return;
			ptype = 'wxpay'; 
			break;
			case 2://点击支付宝支付
			toast('待接口提供');return;
			ptype = 'alipay'; 
			break;
			case 3://点击银联支付
			toast('待接口提供');return;
			break;
			case 4://点击余额支付
			console.log(money+ " "+balance);
			if(parseFloat(balance) < parseFloat(money)){
				toast('您的余额不足请及时充值');
			}else{
				ReBalance();
			}
			break;
		}
	})
	//选择微信支付
//	$('.weixin').on('tap', function(){
//		ptype = 'wxpay'; payment();
//	})
//	//选择支付宝支付
//	$('.alipay').on('tap', function(){
//		ptype = 'alipay'; payment();
//	})
},false)
//减少账户余额
function ReBalance(){
	$.ajax({
		type:"get",
		url:apiRoot+"/home/income/Decbalance",
		data :{
			uid :uid,
			money :money
		},
		success:function(data){
			console.log(data);
			var str = parseFloat(balance) - parseFloat(money);
			plus.storage.setItem('money', str+'');
			source();
			payOrder();
			$('.paymoney').text(money+'元');
			overPay = '1';
		},
		error :function(e){
			console.log(JSON.stringify(e));
		}
	});
}
//时间戳转换成日期
function cdate(date){
	var date = new Date(date);
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var hours = date.getHours();
    var minute = date.getMinutes();
    if (month >= 1 && month <= 9)month = "0" + month;
    if (strDate >= 0 && strDate <= 9)strDate = "0" + strDate;
    if (hours >= 0 && hours <= 9)hours = "0" + hours;
    if (minute >= 0 && minute <= 9)minute = "0" + minute;
    var currentdate = date.getFullYear() + '-' + month + '-' + strDate + " " + hours + ':' + minute;
    return currentdate ? currentdate : '';
}
//日期转换成时间戳格式
function get_unix_time(dateStr){
    var newstr = dateStr.replace(/-/g,'/'); 
    var date =  new Date(newstr); 
    var time_str = date.getTime().toString();
    return time_str.substr(0, 10);
}   
// 检测是否安装支付服务
function checkServices(pc){
	if(!pc.serviceReady){
		var txt=null;
		switch(pc.id){
			case "alipay":
			txt="检测到系统未安装“支付宝快捷支付服务”，无法完成支付操作，是否立即安装？";
			break;
			default:
			txt="系统未安装“"+pc.description+"”服务，无法完成支付，是否立即安装？";
			break;
		}
		plus.nativeUI.confirm(txt,function(e){
			if(e.index==0){
				pc.installService();
			}
		},pc.description);
	}
}
//支付
function payment(){
	//预设订单Id ——> 用户Id+当前时间戳
	var orderid = uid+new Date().getTime();
	if(w){return;}//检查是否请求订单中
	console.log(orderid+" "+money+" "+ptype); 
	if(ptype == 'alipay'){
//		console.log(webRoot + '/pay/Alipay.php?orderid=' + orderid + '&price='+money);return;
		url = webRoot + '/pay/Alipay.php?orderid=' + orderid + '&price='+money;
	}else if(ptype == 'wxpay'){
//		console.log(webRoot + '/pay/index.php?orderid=' + orderid + '&price='+money);return;
		url = webRoot + '/pay/index.php?orderid=' + orderid + '&price='+money+'&type=1';
	}
	w = plus.nativeUI.showWaiting('支付中...',{width:'80px',height:'80px',background:'rgba(0,0,0,0.3)'});
	// 请求支付订单
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
		switch (xhr.readyState) {
			case 4:
			w.close(); 
			w = null;
			if (xhr.status == 200) { 
				var order = xhr.responseText;
				console.log(JSON.stringify(pays[ptype]));
				console.log(order);
				plus.payment.request(pays[ptype], order, function(result) { 
					//对订单进行操作
					source();
					payOrder();
					$('.paymoney').text(money+'元');
					overPay = '1';
				}, function(e) {
					console.log("提示", null, "支付失败");
					console.log("["+e.code+"]："+e.message);
				});
			} else { 
				plus.nativeUI.toast("获取订单信息失败！", null, "捐赠");
			}
			break;
		default:
			break;
		}
	}
	xhr.open('GET', url);
	xhr.send();
}
//添加收入支出记录
function source(){
	$.ajax({
		type:"get",
		url:apiRoot+"?m=home&c=income&a=recharge",
		data :{
			payer :uid,
			earner :doctorid,
			source :'视频咨询',
			money :money,
			tid :77//支出
		},
		dataType :'json',
		success :function(data){
			console.log(JSON.stringify(data));
			if(data > 0){
				toast('支付成功');
			}else{
				toast('支付失败');
			}
		},
		error :function(e){
			errortoast();
		}
	});
}	
//增加一条问诊记录
function payOrder(){
	$.ajax({
		type:"get",
		url:apiRoot+"?m=home&c=chat&a=sendMessage",
		data :{
			sendid :uid,
			receiveid :doctorid,
			bespeak : $('#result').text(),
			status :'0',
			type :'3',
			tid :80
		},
		success :function(data){
			console.log(data);
			wenzhen = data;
			//
			toast('预约成功');
//			toast('预约成功,问诊号：'+wenzhen);
			ws.close();
			//
		},
		error :function(e){
			errortoast();
		}
	});
}
